$.getServices = function() {

    $('#progressPagos').modal({ backdrop: 'static' });

    $("#tblServicios tbody").remove();

    $.ajax({
      url:'controller/controller.php',
      type:'POST',
      data: { option: 'getServices' }
    }).success(function(data){
        var json = eval('(' + data + ')');
        $.each(json, function(i, item) {     

            if (item.status === 'A')
                estado = "checked";
            else
                estado = "";

            row = '<tr id="ser_trServices_' + item.service_id + '"> \
                       <td id="name" style="vertical-align:middle;" class="text-left">'  + item.name              + '</td> \
                       <td id="start_date_active" style="vertical-align:middle;" class="text-right">' + item.start_date_active + '</td> \
                       <td id="end_date_active" style="vertical-align:middle;" class="text-right">' + item.end_date_active   + '</td> \
                       <td style="vertical-align:middle;" class="text-center"><input id="status" type="checkbox" disabled ' + estado + ' ></td> \
                       <td style="vertical-align:middle;" class="text-center"> \
                           <a serviceID="' + item.service_id + '" serviceName="' + item.name + '" id="ser_btnEdit" class="btn btn-warning" href="#"><i class="icon-edit icon-white"></i></a> \
                           <a serviceID="' + item.service_id + '" serviceName="' + item.name + '" id="ser_btnDelete" class="btn btn-danger" href="#"><i class="icon-trash icon-white"></i></a> \
                       </td> \
                   </tr>';

            $('#tblServicios').append(row);
        });
    })
    .error (function (request, status, error) {
        alert(request.responseText); })
    .fail(function(request, error)  {alert("Error obteniendo servicios: " + error);});

    $('#progressPagos').modal('hide');
    
};
    
$.infoService = function(id) {
    $.ajax({
        type: 'post',
        url: 'controller/controller.php',
        data: {option: 'getInfoService', serviceID: id},
        success: function(data) {
            var json = eval('(' + data + ')');
            $.each(json, function(key, val) {
                
                if (key != "status")
                    $('#ser_' + key + '_add').val(val);
                else
                    if ( val == 'A' )
                        $('#ser_status_add').prop('checked', true);
                    else
                        $('#ser_status_add').prop('checked', false);
                
            });
        }
    });
};

$.insertService = function($data) {
    
    $data.push({
        name: 'option',
        value: 'insertService'
    });
    
    $.ajax({
        type: 'post',
        url: 'controller/controller.php',
        data: $.param($data),
        success: function(data) {
            var json = eval('(' + data + ')');
            
            if(typeof json.success == 'undefined'){
                
                var estado = '';

                if ($('#ser_status_add').prop('checked'))
                    estado = 'checked';
                
                row = '<tr id="ser_trServices_' + json.last_id + '"> \
                         <td id="name" style="vertical-align:middle;" class="text-left">'  + $('#ser_name_add').val() + '</td> \
                         <td id="start_date_active" style="vertical-align:middle;" class="text-right">' + $('#ser_start_date_active_add').val() + '</td> \
                         <td id="end_date_active" style="vertical-align:middle;" class="text-right">' + $('#ser_end_date_active_add').val()   + '</td> \
                         <td style="vertical-align:middle;" class="text-center"><input id="status" type="checkbox" disabled ' + estado + ' ></td> \
                         <td style="vertical-align:middle;" class="text-center"> \
                             <a serviceID="' + json.last_id + '" serviceName="' + $('#ser_name_add').val() + '" id="ser_btnEdit" class="btn btn-warning" href="#"><i class="icon-edit icon-white"></i></a> \
                             <a serviceID="' + json.last_id + '" serviceName="' + $('#ser_name_add').val()+ '" id="ser_btnDelete" class="btn btn-danger" href="#"><i class="icon-trash icon-white"></i></a> \
                         </td> \
                     </tr>';
                
                if (json.afterServiceID)
                    $('#ser_trServices_' + json.afterServiceID).after(row);
                else
                    $('#tblServicios').prepend(row);
                
                $('#ser_name_add').val("");
                $('#ser_start_date_active_add').val("");
                $('#ser_end_date_active_add').val("");
                $('#DATA').data('option', '');
                $('#ser_status_add').prop('checked', false);
                $('#modal-editadd-service').modal('hide');
                $('#modal-confirmation-delete').modal('hide');    
            }
            else
                alert("Error: " + json.message + "sql: " + json.sql);

        }
    });     
};

$.updateService = function($data) {
    
    $data.push({
        name: 'serviceID',
        value: $('#DATA').data('id')
    });
    
    $data.push({
        name: 'option',
        value: 'updateService'
    });
    
    $.ajax({
        type: 'post',
        url: 'controller/controller.php',
        data: $.param($data),
        success: function(data) {
            var json = eval('(' + data + ')');
            
            if (json.success === 1) {

                $.updateTrService($data);
                $('#ser_name_add').val("");
                $('#ser_start_date_active_add').val("");
                $('#ser_end_date_active_add').val("");
                $('#DATA').data('option', '');
                $('#ser_status_add').prop('checked', false);
                $('#modal-editadd-service').modal('hide');
                $('#modal-confirmation-delete').modal('hide');

            } else
                alert("ERROR!!");
        }
    }); 
};

$.deleteService = function(serviceID) {
    $.ajax({
          url:'controller/controller.php',
          type:'POST',
          data: { option: 'deleteService', serviceID: serviceID }
      }).success(function(data){
            var json = eval('(' + data + ')');
            if (json.success === 1) {

                $('#ser_trServices_' + serviceID).remove();
                $('#modal-confirmation-delete').modal('hide');

            } else
                alert("ERROR!!");
    });
};

$.updateTrService = function($data) {
    
    $.each($data, function(i, item) { 
        if ( item["name"] == "serviceID" )
            serviceID = item["value"];
    });
    
    $('#ser_trServices_' + serviceID + ' td input#status').prop('checked', false);
    
    $.each($data, function(i, item) { 
        
        switch (item["name"]) {
            case "name":
                $('#ser_trServices_' + serviceID + ' td#name').html(item["value"]);
                break;
            case "start_date_active":
                $('#ser_trServices_' + serviceID + ' td#start_date_active').html(item["value"]);
                break;
            case "end_date_active":
                $('#ser_trServices_' + serviceID + ' td#end_date_active').html(item["value"]);
                break;
            case "status":
                if (item["value"] == "on")
                    $('#ser_trServices_' + serviceID + ' td input#status').prop("checked", true);
                break;
         }
         
    });
    
};

$(document).ready(function(){
    
    //$.getPeriods();
    
    $(document).off('click', '#per_btnAdd').on('click', '#per_btnAdd', function() { 
        $('#period_name').val("");
        $('#period_start_date').val("");
        $('#period_end_date').val("");
        $('#period_num').val("");
        $('#period_year').val("");        
        $('#period_status').prop('checked', false);
        
        $('#DATA').data('option', 'insert');
        $('#DATA').data('id', '');
        $('#modal-editadd-periods #titulo').text('').text('Agregar Período');        
        $("#ui-datepicker-div").css("z-index", "9999");
        $('#modal-editadd-periods').modal('show');
    });
    
    
    
    
    

    $(document).off('click', '#ser_del_service').on('click', '#ser_del_service', function() {    
        var serviceID = $('#ser_del_service').attr('delServiceID');
        $.deleteService(serviceID);
    });
    
    $(document).off('click', '#ser_btnDelete').on('click', '#ser_btnDelete', function() {
        
        var serviceName = $(this).attr('serviceName');
        var serviceID = $(this).attr('serviceID');

        $('#ser_msg_str').text('').text('Desea borrar el servicio de ' + serviceName + '?');
        $('#ser_del_service').attr('delServiceID', serviceID);
        $('#modal-confirmation-delete').modal({ backdrop: 'static' });  
    });    
    
    $(document).off('click', '#ser_btnEdit').on('click', '#ser_btnEdit', function() {
        $('#DATA').data('id', $(this).attr('serviceID'));
        $('#DATA').data('option', 'update');
        $('#modal-editadd-service #titulo').text('').text('Actualizar Servicio');
        $.infoService($(this).attr('serviceID'));
        $("#ui-datepicker-div").css("z-index", "9999");
        $('#modal-editadd-service').modal('show');
    });
    
    $(document).off('click', '#per_btn_cancelar').on('click', '#per_btn_cancelar', function() {    
        $('#ser_name_add').val("");
        $('#ser_start_date_active_add').val("");
        $('#ser_end_date_active_add').val("");
        $('#DATA').data('option', '');
        $('#ser_status_add').prop('checked', false);
        $('#modal-editadd-periods').modal('hide');
    });
    
    $(document).off('click', '#ser_btn_aceptar').on('click', '#ser_btn_aceptar', function() {
        if ($('#DATA').data('option') === 'insert')
                $.insertService($('#form-add').serializeArray());
        else
            if ($('#DATA').data('option') === 'update')
                $.updateService($('#form-add').serializeArray());
    });

    $('#period_start_date, #period_end_date').datepicker( { format: 'dd/mm/yyyy' });  
    $('#period_start_date, #period_end_date').datepicker().on('show', function(ev){
        $(this).datepicker('setValue', $(this).val());
    });
    
    $(document).off('click', '#ser_btnAdd').on('click', '#ser_btnAdd', function() {
        $('#ser_name_add').val("");
        $('#ser_start_date_active_add').val("");
        $('#ser_end_date_active_add').val("");
        $('#DATA').data('option', '');
        $('#ser_status_add').prop('checked', false);
        $('#modal-editadd-service').modal('hide');
        
        $('#DATA').data('option', 'insert');
        $('#DATA').data('id', '');
        $('#modal-editadd-service #titulo').text('').text('Agregar Servicio');        
        $("#ui-datepicker-div").css("z-index", "9999");
        $('#modal-editadd-service').modal('show');
    });

});